package xyz.xpman.prisonerfitness.service;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;

import androidx.annotation.RequiresApi;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import xyz.xpman.prisonerfitness.util.FileUtil;
import xyz.xpman.prisonerfitness.util.StrKit;
import xyz.xpman.prisonerfitness.util.XmlUtil;

@SuppressWarnings("unused")
public class GroupRestTimeUtil {
    private static final int DEFAULT_PROGRESS = 45;
    private static final String PROGRESS_NAME = "progress";
    private static final String PROGRESS_FILE_NAME = "progress.xml";
    @SuppressLint("StaticFieldLeak")
    private static Context context = null;

    private GroupRestTimeUtil() { }

    public static void init(@NotNull Context context) {
        if (null == GroupRestTimeUtil.context) {
            GroupRestTimeUtil.context = context;
        }
    }


    public static int get() {
        final String dataStr = FileUtil.read(getConfigFilePath());

        if (StrKit.isBlank(dataStr)) {
            return DEFAULT_PROGRESS;
        }


        int progress = DEFAULT_PROGRESS;
        String progressStr = XmlUtil.parseToMap(dataStr).get(PROGRESS_NAME);

        if (StrKit.notBlank(progressStr)) {
            try {
                progress = Integer.parseInt(progressStr);
            } catch (NumberFormatException ignore) { }
        }
        return progress;
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public static boolean save(int progress) {
        Map<String, String> data = new HashMap<>(1);
        data.put(PROGRESS_NAME, String.valueOf(progress));

        String xmlString = XmlUtil.toXmlString(data);
        String configFilePath = getConfigFilePath();
        FileUtil.createFile(new File(configFilePath));

        return FileUtil.saveToFile(configFilePath, xmlString);
    }



    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



    private static String getConfigFilePath() {
        File cacheDir = FileUtil.getCacheDir(context, "config");
        return cacheDir.getAbsolutePath() + File.separator + PROGRESS_FILE_NAME;
    }

}
